<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/20 23:24
 */

namespace module\chat\front\input;

use app\model\Role;
use module\ai\model\Channel;
use module\chat\model\Assistant;
use module\chat\model\Unlimited;
use module\chat\model\Visrole;
use module\user\library\Auth;
use mof\Model;
use mof\Request;
use mof\Validate;

class MessageInput
{
    protected array $attrs = [
        'object_type', 'object_id', 'channel_id', 'prompt_text', 'receive_lang', 'is_first'
    ];

    protected array $data = [];

    protected Channel   $channel;
    protected Unlimited $unlimited;
    protected Model     $role;

    public function __construct(Request $request, protected Auth $auth)
    {
        $data = $request->post($this->attrs);
        $data['send_ip'] = $request->ip();
        $this->validate($data);
        $this->data = $data;
    }

    protected function validate($postData): void
    {
        $validate = new Validate();
        $validate->extend('checkTypeId', function ($value, $rule, $data) {
            switch ($data['object_type']) {
                case 'unlimited':
                    $unlimited = Unlimited::where(['id' => $value, 'user_id' => $this->auth->getId()])->find();
                    if (!$unlimited) return '对话不存在';
                    $this->unlimited = $unlimited;
                    return true;
                case 'assistant':
                    $assistant = Assistant::where(['id' => $value, 'status' => 1])->find();
                    if (!$assistant) return '创作助手不存在或已下架';
                    $this->role = $assistant;
                    return true;
                case 'visrole':
                    $visrole = Visrole::where(['id' => $value, 'status' => 1])->find();
                    if (!$visrole) return '角色不存在或已下架';
                    $this->role = $visrole;
                    return true;
                default:
                    return '未知的对话类型';
            }
        })->extend('checkChannelId', function ($value, $rule, $data) {
            $channel = Channel::where(['id' => $value, 'status' => 1])->find();
            if (!$channel) return 'AI通道不存在或已下架';
            return true;
        })->extend('checkContent', function ($value, $rule, $data) {
            return true;
        });

        $validate->rule([
            'object_type|对话类型' => 'require',
            'object_id|对话ID'     => 'require|checkTypeId:1',
            'channel_id|对话通道'  => 'require|checkChannelId:1',
            'prompt_text|发送内容' => 'require|min:2|max:2048|checkContent:1',
        ])->failException()->check($postData);
    }

    public function data(): array
    {
        return $this->data;
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }
}